package tc.crase.cmds;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

import tc.common.utility.GrView;
import tc.common.utility.TcDisplayTransf;
import tc.crase.db.Xattr;
import tc.crase.db.XattrLNK;
import tc.crase.db.XattrSTR;
import tc.crase.db.XattrTPE;
import tc.crase.db.Xdb;
import tc.crase.db.Xobject;
import tc.crase.save.XdbLoadDb;
import tc.crase.sys.XdbEx;
import tc.crase.sys.XdbRoot;
import tc.crase.sys.XdbSys;
import tc.crase.sys.XobjectEx;
import tc.crase.view.ViewList;
import tc.crase.view.ViewPairs;
import tc.crase.view.ViewRoot;

public class CmdUtility extends CmdEx  implements ActionListener {
	
	public CmdUtility() {
	}
	
	public void initializeDialog() {
		super.initializeDialog();
		setLabel("Utility");
		setHint("Coose utility.");

		JButton buttonIdentityList = new JButton("Identity List");
		buttonIdentityList.addActionListener(this);
		buttonIdentityList.setActionCommand("identityList");
		buttonIdentityList.setPreferredSize(new Dimension(SIDEBAR_WIDTH,24));
		buttonIdentityList.setMaximumSize(new Dimension(SIDEBAR_WIDTH,24));
		
		JButton fileButtonDotPort = new JButton("Dot Port");
		fileButtonDotPort.addActionListener(this);
		fileButtonDotPort.setActionCommand("dotPort");
		fileButtonDotPort.setPreferredSize(new Dimension(SIDEBAR_WIDTH,24));
		fileButtonDotPort.setMaximumSize(new Dimension(SIDEBAR_WIDTH,24));

		dialog.add(buttonIdentityList);
		dialog.add(fileButtonDotPort);

		finalizeDialog();
	}
	
	public void enterPoint(Point pt, GrView view) {
	}

	public void enterReset(GrView view) {
	}
	
	public void enterMove(Point pt, GrView view)  {
	}
	
	private void draw(Graphics g, TcDisplayTransf transf, Color background)
	{
	}
	
	public void actionPerformed(ActionEvent e) {
		if ("identityList".equals(e.getActionCommand())) {
			ViewPairs pairs = new ViewPairs();
			String title = "Identical objects";
			ViewRoot.createFrame(pairs, title);
			
			XdbEx xdb = XdbRoot.xdbsys.current;
			for(Xobject object1: xdb) {
				String name1 = object1.getObjectName();
				name1 = name1.replaceAll("\\s+", "");
				
				boolean reached = false;
				
				for(Xobject object2: xdb) {
					if ( ( reached == false ) && (object1 == object2) ) {
						reached = true;
						continue;
					}
					if ( reached == false ) continue;
					
					String name2 = object2.getObjectName();
					name2 = name2.replaceAll("\\s+", "");
					
					if ( name1.equalsIgnoreCase(name2) == false ) continue;
					
					boolean typeMatch = false;
					
					Outer:
					for (Xattr attr1: object1) {
						XattrTPE attrTPE1 = attr1.getAsTPE();
						if (attrTPE1 == null) continue;
						
						for (Xattr attr2: object2) {
							XattrTPE attrTPE2 = attr2.getAsTPE();
							if (attrTPE2 == null) continue;
							
							if ( attrTPE1.id.equals(attrTPE2.id) == false ) continue;
							
							typeMatch = true;
							break Outer;
						}
					}
					
					if ( typeMatch == false ) continue;
					
					pairs.add((XobjectEx)object1, (XobjectEx)object2);
				}
			}
		}
		else if ( "dotPort".equals( e.getActionCommand()) ) {
			dotPort();
		}
	}
	
	public void dotPort() {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("CRASE file", "crase");
	    chooser.setFileFilter(filter);
		int returnVal = chooser.showSaveDialog(null);
		if(returnVal != JFileChooser.APPROVE_OPTION) 
		{	return;
		}
		
		File craseFile = chooser.getSelectedFile();
		
		Xdb xdb = new Xdb();
		XdbLoadDb loader = new XdbLoadDb(xdb);
		loader.load(craseFile, false);

		String dotPath = craseFile.getPath().replaceAll(".crase", ".dot");
		File dotFile = new File(dotPath);
		
		dotSave(xdb, dotFile);
	}
	
	public void dotSave( Xdb xdb, File dotFile ) {
		try {
			if (!dotFile.exists()) dotFile.createNewFile();
			FileWriter writer = new FileWriter(dotFile);
			
			writer.write("graph graphname { \n\n");
			
			for (Xobject object : xdb) {
				writer.write("" + object.getId() + " [label=\"");
				String label = "";
				for (Xattr attr : object) {
					if (attr.getAsTPE() != null) {
						label = label.concat("<").concat(attr.getAsTPE().getValue()).concat(">");
					}
					else if (attr.getAsSTR() != null) {
						XattrSTR attrSTR = attr.getAsSTR(); 
						if (label.isEmpty() == false) label = label.concat(" ");
						label = label.concat(attrSTR.getName().concat(": ").concat(attrSTR.getValue()));
					}
				}
				label.replace('"', '\'');
				writer.write(label);
				writer.write("\"];\n");
			}
			
			writer.write("\n");
			
			for (Xobject object : xdb) {
				for (Xattr attr : object) {
					XattrLNK attrLNK = attr.getAsLNK();
					if (attrLNK == null) continue;
					if (attrLNK.isFirst() == false) continue;
					
					writer.write(object.getId() + " -- " + attrLNK.getOpposite().getParent().getId() + ";\n");
				}
			}
			
			writer.write("}");
			
			writer.close();
		}
		catch (IOException e) {
		}
		finally {
		}
	}
}
